package com.wisdomparking.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wisdomparking.constant.Constants;


/**
 * 字符串处理常用方法
 */
public abstract class ToolString {

    protected final Logger LOG = LoggerFactory.getLogger(getClass());

    /**
     * 字符编码
     */
    public final static String encoding = "UTF-8";

    /**
     * Url Base64编码
     * 
     * @param data
     *            待编码数据
     * @return String 编码数据
     * @throws Exception
     */
    public static String encode(String data) throws Exception {
        // 执行编码
        byte[] b = Base64.encodeBase64URLSafe(data.getBytes(encoding));

        return new String(b, encoding);
    }

    /**
     * Url Base64解码
     * 
     * @param data
     *            待解码数据
     * @return String 解码数据
     * @throws Exception
     */
    public static String decode(String data) throws Exception {
        // 执行解码
        byte[] b = Base64.decodeBase64(data.getBytes(encoding));

        return new String(b, encoding);
    }

    /**
     * URL编码（utf-8）
     * 
     * @param source
     * @return
     */
    public static String urlEncode(String source) {
        String result = source;
        try {
            result = java.net.URLEncoder.encode(source, encoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取bean名称
     * 
     * @param bean
     * @return
     */
    public static String beanName(Object bean) {
        String fullClassName = bean.getClass().getName();
        String classNameTemp = fullClassName.substring(
                fullClassName.lastIndexOf(".") + 1, fullClassName.length());
        return classNameTemp.substring(0, 1) + classNameTemp.substring(1);
    }

    /**
     * 首字母转小写
     * 
     * @param s
     * @return
     */
    public static String firstCharToLowerCase(String s) {
        if (Character.isLowerCase(s.charAt(0))) {
            return s;
        } else {
            return (new StringBuilder())
                    .append(Character.toLowerCase(s.charAt(0)))
                    .append(s.substring(1)).toString();
        }
    }

    /**
     * 首字母转大写
     * 
     * @param s
     * @return
     */
    public static String firstCharToUpperCase(String s) {
        if (Character.isUpperCase(s.charAt(0))) {
            return s;
        } else {
            return (new StringBuilder())
                    .append(Character.toUpperCase(s.charAt(0)))
                    .append(s.substring(1)).toString();
        }
    }

    public static String toCamelNamed(String srcStr, String replaceStr) {
        String newString = "";
        int first = 0;
        while (srcStr.indexOf(replaceStr) != -1) {
            first = srcStr.indexOf(replaceStr);
            if (first != srcStr.length()) {
                newString = newString + srcStr.substring(0, first);
                srcStr = srcStr.substring(first + replaceStr.length(),
                        srcStr.length());
                srcStr = firstCharToUpperCase(srcStr);
            }
        }
        return newString + srcStr;
    }

    public static String camelNamedToUnderline(String srcStr) {
        if (srcStr == null || "".equals(srcStr.trim())) {
            return "";
        }
        String srcStrTable = null,srcStrRow = null;
        if(srcStr.contains(".")){
        	int locals = srcStr.indexOf(".");
        	srcStrRow = srcStr.substring(locals+1);
        	srcStrTable = srcStr.substring(0,locals);
        }else{
        	srcStrRow = srcStr;
        }
        
        int len = srcStrRow.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = srcStrRow.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append("_");
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return srcStrTable==null?sb.toString():srcStrTable+"."+sb.toString();
    }
    
    public static String encodeString(String object, String newCharacterEncoding) {
        return encodeString(object, newCharacterEncoding, null);
    }

    public static String encodeString(String object,
            String newCharacterEncoding, String oldCharacterEncoding) {
        String result;
        try {
            if (oldCharacterEncoding == null) {
                result = new String(object.getBytes(), newCharacterEncoding);
                return result;
            }
            result = new String(object.getBytes(oldCharacterEncoding),
                    newCharacterEncoding);
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 除去字符串中最后的reg字符
     * 
     * @param str
     * @return String
     */
    public static String getDelReg(String str, String reg) {
        StringBuffer sb = new StringBuffer();

        if (null != str && !"".equals(str)) {
            char[] c = (str.trim()).toCharArray();

            int len = reg.equals(String.valueOf(c[c.length - 1])) ? c.length - 1
                    : c.length;

            for (int i = 0; i < len; i++) {
                sb.append(c[i]);
            }
        }

        return sb.toString();
    }
    
    /**
     * 指定字符在字符串第一次出现的位置
     * 
     * @param str
     * @param reg
     * @return int
     */
    public static int firstIndexOf(String str, String reg) {
		Matcher slashMatcher = Pattern.compile(reg).matcher(str);
		int mIdx = 0;
		while (slashMatcher.find()) {
			mIdx++;
			if (mIdx == 1) {
				break;
			}
		}
		return slashMatcher.start();
	}
    
    
    private static final int SIZE = 6;
    private static final String SYMBOL = "*";
    
    /**
     * 数据脱敏
     * 
     * @param value
     * @return
     */
	public static String toConceal(String value) {
		if (null == value || "".equals(value)) {
			return value;
		}
		int len = value.length();
		int pamaone = len / 2;
		int pamatwo = pamaone - 1;
		int pamathree = len % 2;
		StringBuilder stringBuilder = new StringBuilder();
		if (len <= 2) {
			if (pamathree == 1) {
				return SYMBOL;
			}
			stringBuilder.append(SYMBOL);
			stringBuilder.append(value.charAt(len - 1));
		} else {
			if (pamatwo <= 0) {
				stringBuilder.append(value.substring(0, 1));
				stringBuilder.append(SYMBOL);
				stringBuilder.append(value.substring(len - 1, len));

			} else if (pamatwo >= SIZE / 2 && SIZE + 1 != len) {
				int pamafive = (len - SIZE) / 2;
				stringBuilder.append(value.substring(0, pamafive));
				for (int i = 0; i < SIZE; i++) {
					stringBuilder.append(SYMBOL);
				}
				if ((pamathree == 0 && SIZE / 2 == 0) || pamathree != 0) {
					stringBuilder.append(value.substring(len - pamafive, len));
				} else {
					stringBuilder.append(value.substring(len - (pamafive + 1), len));
				}
			} else {
				int pamafour = len - 2;
				stringBuilder.append(value.substring(0, 1));
				for (int i = 0; i < pamafour; i++) {
					stringBuilder.append(SYMBOL);
				}
				stringBuilder.append(value.substring(len - 1, len));
			}
		}
		
		return stringBuilder.toString();
	}
	
	
	/**
	 * 补齐字符
	 * 
	 * @param str
	 * @param len
	 * @param c
	 * @return 
	 */
	public static String repairstr(String str, int len, String c, boolean flag){
		StringBuffer _str = new StringBuffer();
		int _len = str.length();
		int _cs = len - _len;
		
		if(flag){
			for(int i=0;i<_cs;i++){
				_str.append(c);
			}
			_str.append(str);
		}
		else{
			_str.append(str);
			for(int i=0;i<_cs;i++){
				_str.append(c);
			}
		}
		
		return _str.toString();
	}
	
	/**
	 * 生成随机数
	 * @param min
	 * @param max
	 * @return
	 */
	public static String nextInt(final int min, final int max){
		Random rand= new Random();
		int tmp = Math.abs(rand.nextInt());
		return String.valueOf(tmp % (max - min + 1) + min);
	}
	
	/**
	 * 生成验证码
	 * 
	 * @return
	 */
	public static String generateIdentifyingCode(){
		String code = "";
		code = repairstr(nextInt(0, 1000000), 6, "0", true);
		return code;
	}
	
	/**
	 * 生成单号
	 * @param list
	 * @param groupNumber
	 * @return
	 */
	public static String generateSingleNumber(String prefix){
		String singleNumber = ToolDateTime.getNowDate(new Date(), Constants.BASEDATEFROMATNONE) + nextInt(1000, 9999);
		
		if(null!=prefix && !"".equals(prefix)){
			singleNumber = prefix + singleNumber;
		}
		
		return singleNumber;
	}
	
	/**
	 * Get 方式访问 url
	 * @param url
	 * @param queryString
	 * @param charset
	 * @param pretty
	 * @return
	 */
	public static String doGet(String url, String queryString, String charset, boolean pretty) {
		StringBuffer response = new StringBuffer();
		HttpClient client = new HttpClient();
		HttpMethod method = new GetMethod(url);
		try {
			if (StringUtils.isNotBlank(queryString)){
				method.setQueryString(URIUtil.encodeQuery(queryString));
			}
			client.executeMethod(method);
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(method.getResponseBodyAsStream(), charset));
			String line;
			while ((line = reader.readLine()) != null) {
				if (pretty)
					response.append(line).append(System.getProperty("line.separator"));
				else
					response.append(line);
			}
			reader.close();

		} catch (URIException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// method.releaseConnection();
		}
		return response.toString();
	}
	
	public static void main(String[] args) {
//		String t = "";
//		for(int i=0;i<100;i++){
//			t = ToolString.generateSingleNumber("xxxJHZL_");
//			System.out.println(t + "    Length: " + t.length());
//		}
		String url = "http://api.cnpms.cn/v407/Hello/test";
		String res = ToolString.doGet(url, "", "utf-8", false);
		System.out.println(res);
	}
	
}
